package cn.chowx.myjfinal.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;

import cn.chowx.myjfinal.common.BaseController;
import cn.chowx.myjfinal.help.PageHelp;
import cn.chowx.myjfinal.system.model.SysAction;
import cn.chowx.myjfinal.system.model.SysUser;
import cn.chowx.myjfinal.system.model.SysUserRole;

import com.google.common.base.Strings;
import com.jfinal.log.Logger;

/**
 * 用户 controller
 * @author zcqshine
 *
 */
public class SysUserController extends BaseController {
	private static final Logger LOG = Logger.getLogger(SysUserController.class);
	public void index(){
		render("/WEB-INF/login.html");
	}
	
	/**
	 * 导航到用户列表页面
	 */
	public void toListView(){
		render("user.html");
	}
	
	/**
	 * 用户列表
	 */
	public void list(){
		setPageHelp();
		String pageJson = SysUser.DAO.findAll(pageHelp);
		renderJson(pageJson);
	}
	
	public void cud(){
		String oper = getPara("oper");
		
		int id = NumberUtils.toInt(getPara("id"));
		String account = getPara("account");
		String password = getPara("password");
		String nickName = getPara("nickName");
		int sex = NumberUtils.toInt(getPara("sex"));
		String email = getPara("email");
		String userName = getPara("userName");
		int status = NumberUtils.toInt(getPara("status"),1);
		
		int upatePassword = NumberUtils.toInt(getPara("updatePassword"));
		
		SysUser user = new SysUser();
		user.set("id", id);
		user.set("account", account);
		user.set("password", password);
		user.set("nickName", nickName);
		user.set("sex", sex);
		user.set("email", email);
		user.set("userName", userName);
		user.set("status", status);
		
		String msg = null;
		if(!Strings.isNullOrEmpty(oper)){
			switch (oper) {
			case PageHelp.OPER_CREATE:
				msg = save(user);
				break;
			case PageHelp.OPER_UPDATE:
				msg = update(user,upatePassword);
				break;
			case PageHelp.OPER_DELETE:
				msg = delete(user);
				break;
			default:
				break;
			}
		}
		renderJson(msg);
	}
	
	private String save(SysUser user){
		if(user.saveUser()){
			return "添加用户成功";
		}else{
			return "添加用户失败";
		}
	}
	
	private String update(SysUser user,int upatePassword){
		if(user.updateUser(upatePassword)){
			return "更新用户信息成功";
		}else{
			return "更新用户信息失败";
		}
	}
	
	private String delete(SysUser user){
		if(user.delete()){
			return "删除用户成功";
		}else{
			return "删除用户失败";
		}
			
	}
	/*
	@RequiresUser
	public void add(){
		SysUser user = getModel(SysUser.class);
		boolean flag = user.saveUser();
		JsonResponseHelp jrh = new JsonResponseHelp();
		if(flag){
			jrh.setFlag(JsonResponseHelp.FLAG_SUCCESS);
			jrh.setMsg("添加用户成功");
		}else{
			jrh.setFlag(JsonResponseHelp.FLAG_FAILURE);
			jrh.setMsg("添加用户失败");
		}
		renderJson(jrh);
	}
	*/
	
	public void login(){
		SysUser user = getModel(SysUser.class);
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getStr("account"),user.getStr("password"));
		token.setRememberMe(true);
		try{currentUser.login(token);
			user = (SysUser)currentUser.getPrincipal();		  
			setAttr("sysUser",user);
			Set<SysAction> actionSet = user.getSysActions();  //用户能操作的菜单资源
			TreeMap<String, List<SysAction>> actionMap = new TreeMap<>();
			for(SysAction action : actionSet){
				String parentId =  String.valueOf(action.getInt("parentId")); //freemarker 中 map 的 key 默认为 string 类型，故在此处做下转换
				if(actionMap.containsKey(parentId)){
					List<SysAction> list = actionMap.get(parentId);
					if(!list.contains(action)){
						list.add(action);
					}
				}else{
					List<SysAction> list = new ArrayList<>();
					list.add(action);
					Collections.sort(list);
					actionMap.put(parentId, list);
				}
			}
			if(!actionMap.isEmpty()){
				setAttr("rootKey",actionMap.firstKey());  //设置根节点编号
			}
			setAttr("actionMap",actionMap);
			render("/WEB-INF/main/main.html");
		}catch(Exception e){
			e.printStackTrace();
			LOG.error(e.getMessage());
			redirect("/");
		}
	}
	
	/**
	 * 用户登出
	 */
	@RequiresUser
	public void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
	}
	
	/**
	 * 获取角色 json 字符串
	 */
	public void getRoles(){
		int uid = NumberUtils.toInt(getPara("uid"));
		renderJson(SysUser.DAO.getRoleJson(uid));
	}
	
	/**
	 * 更新用户角色
	 */
	public void updateRole(){
		int uid = NumberUtils.toInt(getPara("uid"));
		String roleIdAndChk = getPara("roleIdAndChk");
		if(!Strings.isNullOrEmpty(roleIdAndChk)){
			String[] keyValues = roleIdAndChk.split(",");
			boolean flag = SysUserRole.DAO.saveOrUpdate(uid,keyValues);
			renderJson(flag?"":"操作失败");
		}else{
			renderJson("操作失败");
		}
		
	}
}
